import 'package:flutter/material.dart';
import 'package:kk/dao/search_dao.dart';
import 'package:kk/widget/search_bar.dart';
import 'package:kk/widget/webview.dart';

class SearchPage extends StatefulWidget {
  final bool? hideLeft;
  final String keyword;
  final String hint;

  const SearchPage({Key? key, this.hideLeft, this.keyword = "", this.hint = ""})
      : super(key: key);

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  List searchModels = [];
  String keyword = "";
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          _appBar(),
          MediaQuery.removePadding(
              removeTop: true,
              context: context,
              child: Expanded(
                  flex: 1,
                  child: ListView.builder(
                      itemCount: searchModels.length,
                      itemBuilder: (BuildContext context, int position) {
                        return _item(position);
                      })))
        ],
      ),
    );
  }

  void _onChanged(String text) {
    keyword = text;
    if (text.length == 0) {
      setState(() {
        searchModels = [];
      });
      return;
    }
    print(keyword);
    SearchDao.fetch(keyword).then((model) {
      if (model["keyword"] == keyword) {
        setState(() {
          searchModels = model["k"] ?? [];
        });
      }
    }).catchError((e) {
      print("fail search text");
    });
  }

  void _rightButtonClick() {}

  void _speakClick() {}

  void _inputBoxClick() {}

  _appBar() {
    return Column(
      children: [
        Container(
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  colors: [Color(0x66000000), Colors.transparent],
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter)),
          child: Container(
            padding: EdgeInsets.only(top: 35),
            height: 80,
            decoration: BoxDecoration(color: Colors.white),
            child: SearchBar(
                hideLeft: widget.hideLeft ?? false,
                defaultText: widget.keyword,
                hint: widget.hint,
                leftButtonClick: () {
                  Navigator.pop(context);
                },
                rightButtonClick: _rightButtonClick,
                speakClick: _speakClick,
                inputBoxClick: _inputBoxClick,
                onChanged: _onChanged),
          ),
        )
      ],
    );
  }

  _item(int position) {
    if (searchModels.length == 0) return null;
    dynamic item = searchModels[position];
    var title = item["name"] ?? item["title"] ?? null;
    var url = item["url"] ??
        item["wxUrl"] ??
        item["userHomePageUrl"] ??
        item["appUrl"] ??
        "";
    var districtName = item["districtName"] ?? "";
    var articleCount = item["articleCount"] ?? null;
    var imageUrl = item["imageUrl"] ?? null;

    return GestureDetector(
      onTap: () {
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return WebView(
            url: url,
            title: "详情",
          );
        }));
      },
      child: Container(
        padding: EdgeInsets.all(10),
        decoration: BoxDecoration(
            border: Border(bottom: BorderSide(width: 0.3, color: Colors.grey))),
        child: Row(
          children: [
            imageUrl != null
                ? Container(
                    margin: EdgeInsets.all(1),
                    child: Image.network(
                      imageUrl,
                      width: 26,
                      height: 26,
                    ),
                  )
                : Container(
                    margin: EdgeInsets.all(1),
                    child: Image(
                      image: AssetImage("images/travel_group.png"),
                      width: 26,
                      height: 26,
                    ),
                  ),
            Column(
              children: [
                Container(
                  width: 300,
                  child: _title(title, articleCount),
                ),
                Container(
                  padding: EdgeInsets.only(top: 5),
                  width: 300,
                  child: _subTitle(districtName),
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  _title(title, articleCount) {
    if (title == null) return null;
    List<TextSpan> spans = [];
    spans.addAll(_keywordTextSpans(title, keyword));
    spans.add(TextSpan(
        text: articleCount != null ? "       ${articleCount}篇旅拍" : "",
        style: TextStyle(fontSize: 16, color: Colors.grey)));

    return RichText(text: TextSpan(children: spans));
  }

  Iterable<TextSpan> _keywordTextSpans(title, String keyword) {
    List<TextSpan> spans = [];
    if (title == null || title.length == 0) return spans;
    List<String> arr = title.split(keyword);
    TextStyle normalStyle = TextStyle(fontSize: 16, color: Colors.black87);
    TextStyle keywordStyle = TextStyle(fontSize: 16, color: Colors.orange);
    // "wordwoc".split("w")--> [,ord,oc]
    for (int i = 0; i < arr.length; i++) {
      if ((i + 1) % 2 == 0) {
        spans.add(TextSpan(text: keyword, style: keywordStyle));
      }
      String val = arr[i];
      if (val != null && val.length > 0) {
        spans.add(TextSpan(text: val, style: normalStyle));
      }
    }
    return spans;
  }

  _subTitle(districtName) {
    return RichText(
        text: TextSpan(children: [
      TextSpan(
          text: districtName,
          style: TextStyle(fontSize: 16, color: Colors.orange))
    ]));
  }
}
